package cn.txy.system.service.impl;

import cn.txy.base.service.impl.BaseServiceImpl;
import cn.txy.system.domain.Menu;
import cn.txy.system.mapper.MenuMapper;
import cn.txy.system.query.MenuQuery;
import cn.txy.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> queryPage(MenuQuery menuQuery) {
        return menuMapper.queryPage(menuQuery);
    }

    @Override
    public List<Menu> menuTree() {
        List<Menu> menus = menuMapper.findAll();
        //map
        Map<Long, Menu> map = menus.stream()
                .collect(Collectors.toMap(Menu::getId, menu -> menu));
        List<Menu> list = new ArrayList<>();
        for (Menu menu : menus) {
            if(menu.getParentId() == null){
                list.add(menu);
            }else {
                //子集
                Menu menu1 = map.get(menu.getParentId());
                menu1.getChildren().add(menu);
            }
        }
        return list;
    }
}
